import React, { Component } from 'react'
import { connect } from 'react-redux'
import { actionCreators } from '../live/store/index'
import BBSWrapper from './components/bbs'
import $ from  'jquery'

import {
  TabsWrapper
} from './style.js'

class Room extends Component {
  constructor(props) {
    super(props)
    this.state = {
      idx: 0,
      isT: sessionStorage.getItem('isShow') ? JSON.parse(sessionStorage.getItem('isShow')).isTrial : false,
      time: sessionStorage.getItem('isShow') ? (JSON.parse(sessionStorage.getItem('isShow')).time? JSON.parse(sessionStorage.getItem('isShow')).time: 180000) : 180000,
      isEnd: false,
      isVertical: true
    }
  }
  componentDidMount() {
    let roomId = this.props.match.params.roomId
    if(roomId) {
      this.props.getVideoByPhone({
        roomId
      })
      setTimeout(()=> {
        this.renderPay()
      },1000)
    }
    setTimeout(() => {
      window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', () => {
        this.orientationFun()
      }, false)
    }, 3000);
  }

  renderLive() {
    if(this.state.isEnd) {
      return (
        <div><p style={{lineHeight: '28px', textAlign: 'center', marginTop: '30px', fontSize: '18px'}}>试听结束，请购买课程之后继续观看</p></div>
      )
    }else {
      return (
        <div>
          <div onClick={this.palyByIos.bind(this)} style={{cursor: 'pointer'}}> 
            <video id="myVideo" className="video-js vjs-default-skin vjs-big-play-centered vjs-fluid" controls preload="auto" autoPlay data-setup='{}' style={{width: '100%', height: '300px', cursor: 'pointer'}}>
                <source id="source" style={{cursor: 'pointer'}} src={this.props.video.get('m3u8_url')} type="application/x-mpegURL"></source>
            </video>
          </div>
          {
            this.renderTabs()
          }
        </div>
      )
    }
  }
  
  renderTabs() {
    if(this.state.isT) {
      return (<div></div>)
    }else {
      return (
        <TabsWrapper >
          <ul style={{marginBottom: '1px'}}>
            <li className={this.state.idx === 0 ? 'active': ''} onClick={()=>this.setState({idx: 0})}>
              课程简介
            </li>
            <li className={this.state.idx === 1 ? 'active': ''} onClick={()=>this.setState({idx: 1})}>
              课程评论
            </li>
          </ul>
          {
            this.state.idx === 0 ? <div style={{padding: '10px'}}> {this.props.video.get('description')} </div> : 
              <div style={{ position: 'fixed', width: '100%',height:'100%', overflowY: 'auto', backgroundColor: '#fff',paddingBottom: '300px' }}>
                <div style={{width: '100%', paddingBottom: '10px'}}>
                  <BBSWrapper {...this.props}/>
                </div>
              </div>
          }
        </TabsWrapper>
      )
    }
  }

  // componentWillUnmount() {
  //   window.myVideo.dispose()
  // }

  renderPay() {
    window.myVideo = window.videojs('myVideo', {
      bigPlayButton: true,
      textTrackDisplay: false,
      posterImage: false,
      errorDisplay: false,
      fluid: true
    })
    // window.myVideo.load()
    window.myVideo.play()

    setTimeout(()=> {
      if(!window.myVideo.paused()) {
        document.getElementsByClassName('vjs-big-play-button')[0].remove()
      }
    },300)
    
    if(this.state.isT) {
      setTimeout(() => {
        this.setState({
          isEnd: true
        })
        // myVideo.dispose()
      }, this.state.time);
    }
    console.log($(".vjs-control-bar"))

    var videoPanelMenu = $('.vjs-fullscreen-control')
    videoPanelMenu.before('<div class="vjs-subs-caps-button  vjs-menu-button vjs-menu-button-popup vjs-control vjs-button"  aria-live="polite" aria-expanded="false" aria-haspopup="true">'  
        + '<div class="vjs-menu" role="presentation">'  
        + '<ul class="vjs-menu-content" role="menu">'  
        + '<li class="vjs-menu-item" tabindex="-1" role="menuitemcheckbox" type="1"  οnclick="changeVideo(1)">流畅</li>'  
        + '<li class="vjs-menu-item" tabindex="-1" role="menuitemcheckbox" type="2" οnclick="changeVideo(2)">标清</li>'  
        + '<li class="vjs-menu-item" tabindex="-1" role="menuitemcheckbox" type="3" οnclick="changeVideo(3)">高清</li>'
        + '<li class="vjs-menu-item" tabindex="-1" role="menuitemcheckbox" type="3" οnclick="changeVideo(4)">超清</li>'    
        + '</ul></div>'  
        +'  <button class="vjs-subs-caps-button vjs-control vjs-button" type="button" aria-live="polite" title="清晰度切换" aria-disabled="false">'  
        +'      <span aria-hidden="true" class="vjs-icon-placeholder" type="qxd"></span><span class="vjs-control-text">清晰度切换</span>'  
        +'  </button>'  
        +'</div>'  
    );

    $('.vjs-menu-item').on('click', (e)=> {
      e.stopPropagation()
      let status = e.target.getAttribute('type')
      var ctime= window.myVideo.currentTime();  
      let src = ''
      switch(status) {
        case '1':
          src = this.props.video.get('m3u8_lld_url')
          break;
        case '2':
          src = this.props.video.get('m3u8_lsd_url')
          // window.videojs("liveVideo").src([{type: "application/x-mpegURL", src: this.props.video.get('m3u8_lsd_url')}]);  
          // window.videojs("liveVideo").play();  
          break;
        case '3':
          src = this.props.video.get('m3u8_lhd_url')
          // window.videojs("liveVideo").src([{type: "application/x-mpegURL", src: this.props.video.get('m3u8_lhd_url')}]);  
          // window.videojs("liveVideo").play(); 
          break;
        case '4':
          src = this.props.video.get('m3u8_lud_url')
          // window.videojs("liveVideo").src([{type: "application/x-mpegURL", src: this.props.video.get('m3u8_lud_url')}]);  
          // window.videojs("liveVideo").play(); 
          break;
      }
      window.myVideo.reset()
      window.myVideo.src({type: 'application/x-mpegURL', src})
      window.myVideo.load(src);
      window.myVideo.on('loadedmetadata', function() {
        window.myVideo.play()
        setTimeout(()=> {
          window.myVideo.currentTime(ctime)
        },2000)
      })
      // window.myVideo.play()
      // window.myVideo.currentTime(ctime)
    })

    $("#myVideo video").css('display', 'initial')

    // $('.vjs-fullscreen-control').click(e=> {
      
    //   window.myVideo.requestFullscreen();

    //   window.myVideo.play();

    //   this.setState({
    //     fullScrren: true
    //   })



    //   // alert('key', this.state.isVertical)
    //   //         let h = document.body.clientHeight
    //   //   let w = document.body.clientWidth
    //   //   let vw = h > w ? h: w
    //   //   let vh = h > w ? w: h
    //   //   document.getElementById('myVideo').style.width = vw + 'px'
    //   //   document.getElementById('myVideo').style.height = vh + 'px'
    // })
    // $('.vjs-fullscreen-control').on('click', (e)=> {
    //   // window.screen.orientation.lock('portrait-secondary')
    //   alert('key', this.state.isVertical)
    //   // if(this.state.isVertical) {
    //   //   let h = document.body.clientHeight
    //   //   let w = document.body.clientWidth
    //   //   let vw = h > w ? h: w
    //   //   let vh = h > w ? w: h
    //   //   document.getElementById('myVideo').style.width = vw + 'px'
    //   //   document.getElementById('myVideo').style.height = vh + 'px'
    //   // }
    // })
  }

  isFullScreen() {
    return  !! (
        document.fullscreen || 
        document.mozFullScreen ||                         
        document.webkitIsFullScreen ||       
        document.webkitFullScreen || 
        document.msFullScreen 
     );
  }
  orientationFun() {
    // alert(window.orientation)
    if (window.orientation === 180 || window.orientation === 0) {
    } else {
      if(!this.isFullScreen()) {
        // window.myVideo.requestFullscreen();
        // document.getElementById("myVideo").requestFullscreen()
        document.documentElement.requestFullscreen()
        // $('#videoWrapper').onClick()
        // document.getElementById('videoWrapper').click('full')
        // document.getElementsByClassName('vjs-fullscreen-control')[0].click()
      }
      // setInterval(()=> {
      //   if(!this.isFullScreen()) {
      //     document.getElementsByClassName('vjs-fullscreen-control')[0].click()
      //   }
      // }, 1000)
      // console.log(document.getElementsByClassName('vjs-fullscreen-control')[0].click())
    }
  }

  componentWillUnmount() {
    window.myVideo.dispose()
  }

  palyByIos(e) {
    if(e.target.getAttribute('type')=== 'qxd') {
      $('.vjs-menu').css('display', 'block')
      setTimeout(()=> {
        $('.vjs-menu').css('display', 'none')
      },2000)
      return
    }
    // if(e.target.getAttribute('title') === 'Fullscreen') {
    //   window.myVideo.requestFullscreen()
    // }
    
    if(window.myVideo.paused()) {
      window.myVideo.play()
    }else {
      window.myVideo.pause()
    }
  }
  
  renderVideo() {
    if(this.props.video.get('m3u8_lsd_url')) {
      if (this.state.isEnd) {
        return (
          <div>
              <p style={{lineHeight: '28px', textAlign: 'center', marginTop: '30px', fontSize: '18px'}}>试听已结束，请购买后观看！</p>
          </div>
        )
      } else {
        return (
          <div style={{position: 'fixed', width: '100%', top: '0px', bottom: '0px'}}>
            {
             <div onClick={this.palyByIos.bind(this)} style={{cursor: 'pointer'}}>
              <video id="myVideo" className="video-js vjs-default-skin vjs-big-play-centered vjs-fluid" controls  autoPlay  preload="auto" data-setup='{}' style={{width: '100%', height: '300px'}}>
                <source id="source" src='http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8' type="application/x-mpegURL"></source>
              </video>
            </div>
            }
            {
              this.renderTabs()
            }
          </div>
        )
      }
    }
  }

  render() {
    return (
      <div>
        {
          this.props.video.get('type') === 'JoyActivity' ? this.renderLive() : this.renderVideo()
        }
      </div>
    )
  }
}

const mapState = (state) => {
  return {
    video: state.getIn(['live', 'live']),
    comment: state.getIn(['live', 'comment']),
    liveImg: state.getIn(['live','liveImg']),
  }
}

const mapDispatch = (dispatch) => {
  return {
    getVideoByPhone(params) {
      dispatch(actionCreators.getVideoByPhone(params))
    },
    addComment(params) {
      dispatch(actionCreators.addComment(params))
    },
    reply(params) {
      dispatch(actionCreators.reply(params))
    },
    getComment(params) {
      dispatch(actionCreators.getComment(params))
    }
  }
}

export default connect(mapState, mapDispatch)(Room) 